package com.mrduan.otgfilemanager.ui.getstrong;

import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.net.Uri;
import android.os.Environment;
//import android.os.storage.StorageManager;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.github.mjdev.libaums.UsbMassStorageDevice;
import com.github.mjdev.libaums.fs.FileSystem;
import com.github.mjdev.libaums.fs.UsbFile;
import com.mrduan.otgfilemanager.App;
import com.mrduan.otgfilemanager.Config;
import com.mrduan.otgfilemanager.R;
import com.mrduan.otgfilemanager.ui.SplashActivity;
import com.mrduan.otgfilemanager.ui.main.MainActivity;
import com.mrduan.otgfilemanager.web.MeidaNanoHTTPD;
import com.orhanobut.logger.Logger;
import com.shike.baselibrary.utils.PermissionUtils;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.Deque;

public class GetStrongActivity extends AppCompatActivity {

    private static final String ACTION_USB_PERMISSION = "com.github.mjdev.libaums.USB_PERMISSION";
    private static final String TAG = GetStrongActivity.class.getSimpleName();

    private Deque<UsbFile> dirs = new ArrayDeque<UsbFile>();
    private FileSystem currentFs;

    private Intent serviceIntent = null;
    UsbMassStorageDevice[] massStorageDevices;
    private int currentDevice = -1;

    private long time = 0;

    String key = "UdisConfig.cong";

    public static boolean hasSdCard = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);

    }

    @Override
    protected void onResume() {
        super.onResume();
        hasSdCard = false;
        PermissionUtils.requestMultiPermissions(this,null);

        new Thread(){
            @Override
            public void run() {
                GetSdCard sdCard = new GetSdCard(GetStrongActivity.this);
                sdCard.startCheck();
            }
        }.start();
//
        init();
    }

    public static MeidaNanoHTTPD http ;

    private void init() {

        try {
            http = new MeidaNanoHTTPD();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String brand = android.os.Build.BRAND;
        if (brand.equals("oppo") || brand.equals("vivo")) {
            findViewById(R.id.need_open_otg).setVisibility(View.VISIBLE);
        }

        TextView version = findViewById(R.id.version);
        version.setText(App.VERSION );

        IntentFilter filter = new IntentFilter();
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        registerReceiver(mUsbReceiver, filter);
        IntentFilter filters = new IntentFilter(ACTION_USB_PERMISSION);
        registerReceiver(mUsbReceiver, filters);

        discoverDevice(getIntent());

        findViewById(R.id.exit_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.exit(0);
            }
        });
        findViewById(R.id.open_otg).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent =  new Intent(Settings.ACTION_SETTINGS);
                startActivity(intent);
            }
        });


    }



    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            Logger.d("----------------------------------------------");
            String action = intent.getAction();
            switch (action) {
                case ACTION_USB_PERMISSION://接受到自定义广播
                    UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

                    Logger.d(time + "");

                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { //允许权限申请
                        if (usbDevice != null) {
                            //Do something
                            setupDevice();
                        }
                    } else {
                        Toast.makeText(context, "用户未授权，读取失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case UsbManager.ACTION_USB_DEVICE_ATTACHED://接收到存储设备插入广播
                    UsbDevice device_add = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (device_add != null) {
                        time++;
//                        Toast.makeText(context, "接收到存储设备插入广播", Toast.LENGTH_SHORT).show();
                        discoverDevice(intent);
                    }
                    break;
                case UsbManager.ACTION_USB_DEVICE_DETACHED://接收到存储设备拔出广播
                    UsbDevice device_remove = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (device_remove != null) {
//                        Toast.makeText(context, "接收到存储设备拔出广播", Toast.LENGTH_SHORT).show();
                        discoverDevice(intent);
                    }
                    break;
            }
        }
    };


    public static UsbFile root;

    /**
     * Sets the device up and shows the contents of the root directory.
     */
    private void setupDevice() {
        try {
            massStorageDevices[currentDevice].init();

            currentFs = massStorageDevices[currentDevice].getPartitions().get(0).getFileSystem();

            root = currentFs.getRootDirectory();

            if (hasSdCard) {
                finish();
                return;
            }

            UsbFile[] f = root.listFiles();

            boolean isU = false;// 是否是标记的u盘
            String appName = null;

            for (UsbFile arg : f) { // 循环 先查一边U盘
                if (arg.getName().equals(key)) {
                    isU = true;
                }
                if (arg.getName().indexOf("apk") != -1) {
                    if (!arg.getName().equals(App.VERSION + ".apk")) {
                        appName = arg.getName();
                    }
                }
            }

            if (isU) { // 找到带有标记的U盘

                if (appName != null) { // 有新的版本
                    final String app = appName;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            downLoadApk(Config.Url + Uri.encode(app));
                        }
                    });
                } else {
                    for (UsbFile arg : f) {

                        if (Config.isNumeric(arg.getName())) {
                            int i = Integer.valueOf(arg.getName());
                            if (i <= 50) {
                                UsbFile[] list = arg.listFiles();
                                String xx = arg.getName();
                                for (UsbFile a : list) {
                                    String mm = a.getName();
                                    if (a.isDirectory()) {
                                        Config.oneScreenUsbFiles.add(a);
                                        break;
                                    }
                                }
                            } else if (i <= 100) {
                                UsbFile[] list = arg.listFiles();
                                for (UsbFile a : list) {
                                    if (a.isDirectory()) {
                                        Config.threeScreenUsbFiles.add(a);
                                        break;
                                    }
                                }
                            } else {
                                UsbFile[] list = arg.listFiles();
                                for (UsbFile a : list) {
                                    if (a.isDirectory()) {
                                        Config.twoScreenUsbFiles.add(a);
                                        break;
                                    }
                                }
                            }
                        } else {
                            if (arg.getName().equals("share")) {
                                UsbFile[] shares = arg.listFiles();
                                for (UsbFile share : shares) {
                                    if (share.getName().equals(App.shareKey)) {
                                        Config.shareUsbFile = share;
                                    }
                                }
                            }
                        }

                    }
                    if (hasSdCard) {
                        finish();
                        return;
                    }
                    hasSdCard = true;
                    startActivity(new Intent(GetStrongActivity.this, MainActivity.class));
                    finish();
                }
            }

        } catch (IOException e) {
            Log.e(TAG, "error setting up device", e);
            showToastMsg("错误");
        }

    }


    /**
     * Searches for connected mass storage devices, and initializes them if it
     * could find some.
     */
    private void discoverDevice(Intent intent) {
        UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        massStorageDevices = UsbMassStorageDevice.getMassStorageDevices(this);

        if (massStorageDevices.length == 0) {
            Log.w(TAG, "no device found!");
            showToastMsg("没有设备");
            return;
        }
        currentDevice = 0;

        UsbDevice usbDevice = (UsbDevice) getIntent().getParcelableExtra(UsbManager.EXTRA_DEVICE);

        if (usbDevice != null && usbManager.hasPermission(usbDevice)) {
            Log.d(TAG, "received usb device via intent");

            showToastMsg("接受到usb");
            if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { //允许权限申请
                if (usbDevice != null) {
                    //Do something
                    setupDevice();
                }
            }
            setupDevice();
        } else {
            showToastMsg("usbDevice==nil");
            PendingIntent permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(
                    ACTION_USB_PERMISSION), 0);
            usbManager.requestPermission(massStorageDevices[currentDevice].getUsbDevice(), permissionIntent);
        }
    }


    /*
	 * 02 * 从服务器中下载APK 03
	 */
    public void downLoadApk(final String apk_url) {
        final ProgressDialog pd = new ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setCancelable(false);
        pd.setCanceledOnTouchOutside(false);
        pd.setMessage("正在下载更新");
        pd.show();

        String ph = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/snss";
        File file = new File(ph + File.separator + "snr.apk");

        RequestParams params = new RequestParams(apk_url);
        params.setSaveFilePath(file.getAbsolutePath());
        x.http().get(params, new Callback.ProgressCallback<File>() {
            @Override
            public void onWaiting() {
            }

            @Override
            public void onStarted() {
            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                pd.setMax((int) total);
                pd.setProgress((int) current);
            }

            @Override
            public void onSuccess(File result) {
                installApk(result);
                pd.dismiss(); // 结束掉进度条对话框
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });

    }

    // 安装apk
    protected void installApk(File file) {
        if (!file.exists()) {
            Logger.d("不是文件");
        } else {
            Logger.d(file.getPath());
        }
        try {
            Intent intent = new Intent();
            // 执行动作
            intent.setAction(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            // 执行的数据类型
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            startActivity(intent);
        } catch (Exception e) {
        }

    }


    private void showToastMsg(String msg) {
//        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }

}
